package cc.eddic.pratice.programmingparadigms.nginxlog.impl;

import cc.eddic.pratice.programmingparadigms.nginxlog.*;
import lombok.extern.slf4j.Slf4j;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
public class LogReportCxmImpl implements LogReport {


    @Override
    public PageViewsAndUniqueVisitors pageViewsAndUniqueVisitors(List<NginxLogItem> items) {
        long uniqueVisitors = items.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(o -> o.getIp()+o.getUserAgent()))),ArrayList::new )
        ).size();
        return new PageViewsAndUniqueVisitors(items.size(), uniqueVisitors);
    }

    @Override
    public Map<Integer, PageViewsAndUniqueVisitors> pageViewsAndUniqueVisitorsByHour(List<NginxLogItem> items) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        return items.stream().collect(Collectors.groupingBy( hour-> LocalDateTime.parse(hour.getTime(),formatter).toLocalTime().getHour()))
                .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, pvUv -> pageViewsAndUniqueVisitors(pvUv.getValue())));
    }

    @Override
    public List<PathModel> pageViewsAndUniqueVisitorsByPath(List<LogItem> items) {
        return items.stream().collect(Collectors.groupingBy(LogItem::getPath)).entrySet().stream().map(stringListEntry -> pathModel(stringListEntry.getKey(),stringListEntry.getValue()))
                .sorted(Comparator.comparing(PathModel::getPv).reversed()).collect(Collectors.toList());
    }

    public PathModel pathModel(String path,List<LogItem> items){
        long pageView=items.size();
        long uniqueVistors=items.stream().collect(Collectors.groupingBy(item -> item.getIp() + item.getUserAgent())).size();
        return new PathModel(path,pageView,uniqueVistors);
    }


}
